package com.netease.xone.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import protocol.meta.Source;
import protocol.meta.User;

import Utils.StackTraceUtil;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts.MENU_ID;
import com.netease.xone.R;
import com.netease.xone.adapter.AdapterTip;
import com.netease.xone.itemview.ItemViewTipBase;
import com.netease.xone.view.MainTitlePopupWindow1;

import db.manager.ManagerDiscussTip;


public class FragmentTipUserOrSource extends FragmentTipBase implements OnClickListener {
    private static final String TAG = FragmentTipUserOrSource.class.getSimpleName();
    
    private int mMainSelectedIndex = 0;
    
    // 输入框内容
    private String mUser;
    private String mSource;
    
    private List<String> mMainTitleList;
    
    private AdapterTip mAdapterUser;
    private AdapterTip mAdapterSource;
    private ActionBar mActionBar;
    
    public static FragmentTipUserOrSource newInstance(Parcelable obj) {
        FragmentTipUserOrSource f = new FragmentTipUserOrSource();
        Bundle b = new Bundle();
        b.putParcelable("obj", obj);
        f.setArguments(b);
        return f;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        super.onCreate(savedInstanceState);
        mActionBar = getSherlockActivity().getSupportActionBar();
        mType = ItemViewTipBase.TYPE_USER;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    		Bundle savedInstanceState) {
    	View view = super.onCreateView(inflater, container, savedInstanceState);
    	if (null != mLetterIndexView) {
    		mLetterIndexView.setVisibility(View.VISIBLE);
    	}
    	return view;
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	NTLog.d(TAG, StackTraceUtil.getMethodName());
	    
    	if (null == mActionBar.getCustomView()) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_main_custom_title,
                    null);
            view.setOnClickListener(this);
            ActionBar.LayoutParams params = new ActionBar.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT,
                    Gravity.LEFT);
            mActionBar.setCustomView(view, params);
            mMainTitleList = new ArrayList<String>();
            mMainTitleList.add("@好友");
            mMainTitleList.add("@资讯源");
            setMainTitle(mMainSelectedIndex);
        }
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setDisplayShowCustomEnabled(true);
        
	    com.actionbarsherlock.view.MenuItem item = menu.add(Menu.NONE, MENU_ID.menu_discuss_send, 0, "done");
	    item.setIcon(R.drawable.icon_action_done_selector);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    }
    
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		NTLog.d(TAG, StackTraceUtil.getMethodName());
		switch (item.getItemId()) {
		case MENU_ID.menu_discuss_send:
			processCheck();
			onLeftTopBack();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
    private void processCheck() {
        String value = null;
        String name = null;
        HashMap<Integer, String> hashMap = null;
        Set<Entry<Integer, String>> set = null;
        List<User> list = null;
        List<Source> list1 = null;
        Integer pos = null;
        
        // 获取选中好友
        if (null != mAdapterUser) {
            hashMap = mAdapterUser.getCheckHashMapUser();
            set = hashMap.entrySet();
            list = new ArrayList<User>();
            for (Entry<Integer, String> entry : set) {
            	pos = entry.getKey();
                name = entry.getValue();
                if (!TextUtils.isEmpty(name)) {
                	list.add((User)mAdapterUser.getItem(pos));
                    if (TextUtils.isEmpty(value)) {
                        value = "@" + name + " ";
                    } else {
                        value = value + "@" + name + " ";
                    }
                }
            }
            ManagerDiscussTip.replaceUser(list, true);
        }
        
        // 获取选中订阅源
        if (null != mAdapterSource) {
            hashMap = mAdapterSource.getCheckHashMapSource();
            set = hashMap.entrySet();
            list1 = new ArrayList<Source>();
            for (Entry<Integer, String> entry : set) {
            	pos = entry.getKey();
                name = entry.getValue();
                if (!TextUtils.isEmpty(name)) {
                	list1.add((Source)mAdapterSource.getItem(pos));
                    if (TextUtils.isEmpty(value)) {
                        value = "@" + name + " ";
                    } else {
                        value = value + "@" + name + " ";
                    }
                }
            }
            ManagerDiscussTip.replaceSource(list1, true);
        }
        
        sendData(value);
    }
    
    /**
     * 屏蔽掉item选中
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }
    
    @Override
    protected void onTabChange(int index) {
        mType = index;
        
        int hint = 0;
        String value = null;
        if (ItemViewTipBase.TYPE_USER == mType) {
            mSource = mFilter;
            value = mUser;
            hint = R.string.tip_user;
        } else if (ItemViewTipBase.TYPE_SOURCE == mType) {
            mUser = mFilter;
            value = mSource;
            hint = R.string.tip_source;
        }
        
        mSearchText.setText(value);
        
        if (!TextUtils.isEmpty(value)) {
            mSearchText.setSelection(value.length());
        } else {
        	if (hint > 0) {
        		mSearchText.setHint(hint);	
        	}
        }
    }
    
    @Override
    protected CursorAdapter getAdapter() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        AdapterTip adapter = null;
        if (ItemViewTipBase.TYPE_USER == mType) {
            if (null == mAdapterUser) {
                mAdapterUser = new AdapterTip(getActivity(), null, ItemViewTipBase.TYPE_USER);
            }
            adapter = mAdapterUser;
        } else if (ItemViewTipBase.TYPE_SOURCE == mType) {
            if (null == mAdapterSource) {
                mAdapterSource = new AdapterTip(getActivity(), null, ItemViewTipBase.TYPE_SOURCE);
            }
            adapter = mAdapterSource;
        }
        adapter.setAlphabetIndexer(mAlphaIndex);
        return adapter;
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " id=" + id);
        switch (id) {
            case R.id.custom_title:
                new MainTitlePopupWindow1(getActivity(), 
                        mActionBar, 
                        this,
                        mMainTitleList, 
                        mMainSelectedIndex);
                break;
            default:
                if (id != mMainSelectedIndex) {
                    setMainTitle(id);
                    onTabChange(id);
                    onResetData();
                }
                break;
        }
    }
    
    private void setMainTitle(int index) {
        mMainSelectedIndex = index;
        
        ((TextView)mActionBar.getCustomView().findViewById(R.id.textview1)).setText(mMainTitleList.get(mMainSelectedIndex));
    }
}
